﻿using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;

namespace Zijian666
{
    /// <summary>
    /// 程序入口
    /// </summary>
    public class Program
    {
        /// <summary>
        /// 程序入口
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello Ccli!");
            if (args.Length != 1)
            {
                Console.WriteLine("exit..");
                Console.ReadLine();
                return;
            }

            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Bind(new IPEndPoint(IPAddress.Loopback, int.Parse(args[0])));
            socket.Listen(10);
            Console.WriteLine("等待主程序接入..." + args[0]);
            var client = socket.Accept();
            var source = new CancellationTokenSource();
            client.ListenReceive((_, str) =>
            {
                //Console.WriteLine(string.Join("\\", str.ToCharArray().Select(x => (int)x)));
                Console.Write(str);
            }, source.Token);
            Task.Run(() =>
            {
                while (true)
                {
                    Thread.Sleep(1000);
                    if (!client.CheckAlive())
                    {
                        Environment.Exit(-1);
                        return;
                    }
                }
            });
            while (true)
            {
                var str = Console.ReadLine();
                if (str == "exit")
                {
                    source.Cancel();
                    Console.WriteLine("按任意键退出");
                    Console.ReadLine();
                    return;
                }
                if (!string.IsNullOrWhiteSpace(str))
                {
                    client.Send(str);
                }
            }
        }
    }
}
